<template>
  <div>
    <el-card class="box-card">
      <h1>修改菜品</h1>
      <el-form @submit.prevent="updateDish" label-width="100px">
        <el-form-item label="选择菜品:" required>
          <el-select v-model="selectedDishId" placeholder="请选择菜品" @change="loadDish" style="width: 100%;">
            <el-option v-for="dish in dishes" :key="dish.id" :label="dish.name" :value="dish.id"></el-option>
          </el-select>
        </el-form-item>
        <div v-if="selectedDishId">
          <el-form-item label="名称:" required>
            <el-input v-model="currentDish.name" placeholder="请输入菜品名称"></el-input>
          </el-form-item>
          <el-form-item label="描述:">
            <el-input type="textarea" v-model="currentDish.description" placeholder="请输入菜品描述"></el-input>
          </el-form-item>
          <el-form-item label="图片:">
            <el-upload
              action=""
              list-type="picture"
              :auto-upload="false"
              :on-change="handleImageChange"
              :file-list="fileList"
              accept="image/*"
              capture="camera"
            >
              <el-button size="small" type="primary">选择图片</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="updateDish">保存</el-button>
            <el-button size="small" @click="resetForm">取消</el-button>
          </el-form-item>
        </div>
        <el-alert v-else type="info" title="请选择一个菜品进行修改" show-icon></el-alert>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import Compressor from 'compressorjs';
import apiClient from '../api';  // 确保路径正确

export default {
  data() {
    return {
      dishes: [],
      selectedDishId: null,
      currentDish: {
        name: '',
        description: '',
        image_url: ''
      },
      newImage: null,
      fileList: []
    };
  },
  methods: {
    async fetchDishes() {
      try {
        const response = await apiClient.get('/dishes');
        this.dishes = response.data;
        if (this.$route.params.id) {
          this.selectedDishId = parseInt(this.$route.params.id, 10);
          this.loadDish(this.selectedDishId);
        }
      } catch (error) {
        console.error('Error fetching dishes:', error);
      }
    },
    loadDish(dishId) {
      const selectedDish = this.dishes.find(dish => dish.id === dishId);
      if (selectedDish) {
        this.currentDish = { ...selectedDish };
        this.fileList = selectedDish.image_url ? [{ name: selectedDish.image_url, url: this.getDishImageUrl(selectedDish.image_url) }] : [];
      }
    },
    getDishImageUrl(imageUrl) {
      return `${apiClient.defaults.baseURL}${imageUrl}`;
    },
    handleImageChange1_nouse(file, fileList) {
      this.fileList = fileList;

      if (file.size > 500 * 1024) {  // 文件大于 500k 时进行压缩
        new Compressor(file.raw, {
          quality: 0.6,
          success: (compressedResult) => {
            this.newImage = compressedResult;
          },
          error: (err) => {
            console.error('压缩图片失败', err);
            this.newImage = file.raw;
          },
        });
      } else {
        this.newImage = file.raw;
      }

      this.saveFormState();
    },
    handleImageChange(file, fileList) {
      this.fileList = fileList;
      const maxSize = 200 * 1024;  // 设置最大文件大小为200k
      // 判断文件大小是否大于200k，如果大于则进行压缩
      if (file.size > maxSize) {  // 文件大于200k时进行压缩
        let quality = maxSize / file.size;  // 动态计算初始压缩质量
        quality = quality < 0.1 ? 0.1 : quality;  // 确保质量不低于0.1
        let currentFile = file.raw;
        // 定义压缩图片方法，如果压缩后文件仍然大于200k，则继续压缩
        const compressImage = (file, quality, callback) => {
          console.log(`1次压缩，当前压缩质量：${quality}，压缩前图片大小：`, file.size);
          new Compressor(file, {
            quality: quality,
            success: (compressedResult) => {
              if (compressedResult.size > maxSize && quality > 0.1) {
                // 如果压缩后仍然大于200k并且质量大于0.1，继续压缩
                compressImage(compressedResult, quality - 0.05, callback);
              } else {
                callback(compressedResult);
              }
            },
            error: (err) => {
              console.error('压缩图片失败', err);
              callback(file);  // 失败时使用原文件
              console.log('压缩图片失败:', compressedResult.size)
            }
          });
        };
        // 调用压缩图片方法
        compressImage(currentFile, quality, (result) => {
          this.newImage = result;
          this.saveFormState();
          console.log('图片压缩后大小:', result.size)
        });
        // 原始图片文件小于200k时，直接使用原始图片
      } else {
        this.newImage = file.raw;
        this.saveFormState();
      }
    },
    saveFormState() {
      localStorage.setItem('editDishForm', JSON.stringify({
        selectedDishId: this.selectedDishId,
        currentDish: this.currentDish,
        fileList: this.fileList
      }));
    },
    loadFormState() {
      const savedState = localStorage.getItem('editDishForm');
      if (savedState) {
        const { selectedDishId, currentDish, fileList } = JSON.parse(savedState);
        this.selectedDishId = selectedDishId;
        this.currentDish = currentDish;
        this.fileList = fileList;
      }
    },
    async updateDish() {
      const maxSize = 500 * 1024;  // 设置最大文件大小为500k

      // 检查压缩后的图片大小
      if (this.newImage && this.newImage.size > maxSize) {
        ElMessage.error('图片无法压缩至 500k 以下，请选择更小的图片。');
        return;
      }
      const formData = new FormData();
      formData.append('name', this.currentDish.name);
      formData.append('description', this.currentDish.description);
      if (this.newImage) {
        formData.append('image', this.newImage);
      } else {
        formData.append('image_url', this.currentDish.image_url);
      }

      try {
        await apiClient.put(`/dishes/${this.currentDish.id}`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        ElMessage.success('菜品修改成功!');
        localStorage.removeItem('editDishForm');
        this.resetForm();
        this.fetchDishes();
      } catch (error) {
        console.error('Error updating dish:', error);
        ElMessage.error('修改菜品失败.');
      }
    },
    resetForm() {
      this.selectedDishId = null;
      this.currentDish = {
        name: '',
        description: '',
        image_url: ''
      };
      this.newImage = null;
      this.fileList = [];
    }
  },
  mounted() {
    this.loadFormState();
    this.fetchDishes();
  },
  watch: {
    '$route.params.id': function(newId) {
      if (newId) {
        this.selectedDishId = parseInt(newId, 10);
        this.loadDish(this.selectedDishId);
      } else {
        this.selectedDishId = null;
      }
    }
  }
};
</script>

<style scoped>
.box-card {
  max-width: 600px;
  margin: 10px auto;
  padding: 10px;
}
@media (max-width: 600px) {
  .box-card {
    margin: 10px;
    padding: 10px;
  }
  .el-form-item__content {
    display: flex;
    flex-direction: column;
  }
}
</style>